<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>表格增删改功能实现</title>
<link rel="stylesheet" href="http://cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.min.css" />
<style>
body{margin: 0;}  
.main{                
    width: 600px;  
    margin-top: 10px;  
    margin-left:auto;  
    margin-right:auto;  
}  
.operation{
    margin: 20px 0 20px;
}
</style>
</head>
<body>
<div class="main">
<div class="operation">
    <button class="btn btn-primary" id="add_tr">新增</button>
    <button class="btn btn-danger" id="del_tr">删除</button>
    <input type="text" width="80px" class="am-group" id="filtertxt" />
    <button class="btn btn-primary" id="search">搜索</button>
    <button class="btn btn-primary" id="init_search">清空筛选条件</button>
</div>
<table class="table table-bordered" id="itable">
    <thead>
        <tr> 
            <th><input type="checkbox" id="select_all" name="" value="" ></th>    
            <th>序号</th>
            <th>姓名</th>
            <th>年龄</th>
            <th>盐值</th>
            <th>成绩</th>
            <th>身高</th>
            <th>操作</th>
        </tr>
    </thead>
    <tbody>
    </tbody>
</table>
<!-- 数据分页 -->
<div class="operation" id="page"></div>
<!--修改信息模块弹窗-->
<div class="modal fade" id="update" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">  
    <div class="modal-dialog">  
        <div class="modal-content">  
            <div class="modal-header">  
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>  
                <h4 class="modal-title" id="modal_title">修改信息</h4>  
            </div>  
            <div class="modal-body">  
                姓名：<input class="form-control" type="text" name="name" id="ed_name" />   <br />
                年龄：<input class="form-control" type="text" name="age" id="ed_age" />   <br />
                盐值：<input class="form-control" type="text" name="look" id="ed_look" />   <br />
                成绩：<input class="form-control" type="text" name="score" id="ed_score" />   <br />
                身高：<input class="form-control" type="text" name="stature" id="ed_stature" />   <br />
            </div>  
            </div>  
            <div class="modal-footer">  
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>  
                <button type="button" class="btn btn-primary" id="revise_update">提交更改</button>  
            </div>  
        </div>  
        <!-- /.modal-content -->  
    </div>  
    <!-- /.modal --> 
<!--添加信息模态弹窗-->
<div class="modal fade" id="addmodal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">  
    <div class="modal-dialog">  
        <div class="modal-content">  
            <div class="modal-header">  
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>  
                <h4 class="modal-title" id="modal_title">新增</h4>  
            </div>  
            <div class="modal-body">  
                姓名：<input class="form-control" type="text" name="name" id="ad_name" />   <br />
                年龄：<input class="form-control" type="text" name="age" id="ad_age" />   <br />
                盐值：<input class="form-control" type="text" name="look" id="ad_look" />   <br />
                成绩：<input class="form-control" type="text" name="score" id="ad_score" />   <br />
                身高：<input class="form-control" type="text" name="stature" id="ad_stature" />   <br />
            </div>  
            <div class="modal-footer">  
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>  
                <button type="button" class="btn btn-primary" id="add_info">提交</button>  
            </div>  
        </div>  
        <!-- /.modal-content -->  
    </div>  
    <!-- /.modal -->  
</div> 
</div>

<!--第三方插件引入-->
<script src="http://cdn.bootcss.com/jquery/1.11.3/jquery.min.js"></script>  
<script src="http://cdn.bootcss.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script>
//模拟表格数据
var data = [];
for(var i = 0; i < 100; i++){
    var object = {
      "name":"学生" + (i+1),
      "age":Math.round(Math.random() * 30),
      "look":Math.round(Math.random() * 5) + "颗星",
      "score":Math.round(Math.random() * 100) + "分",
      "stature":Math.round(Math.random() * 200) + "cm"
  };
  data.push(object);
}
var operations = {
el:"",  //挂载点
data:[],  //数据
is_select:false,  //是否全选
filterArr:[],  //符合条件的数据
init:function(options){
    this.el = options.el;
    this.data = options.data;

    //使用分页对象进行数据渲染
    paging.init({"data":this.data,"el":this.el});

},
//单行删除
delTr:function(){
    var that = this;
    var tr_del = $(that.el).find(".tr-del");
    for(var i = 0; i < tr_del.length; i++){
        tr_del[i].onclick = function(){
            var index = $(this).parents("tr").attr("id");
            var res = confirm("确定要删除么？");
            if(res == true){
                //删除当前行
                $(this).parents("tr").remove();
                //更新操作数据
                that.data.splice(index,1);
                //重新渲染表格
                paging.init({"data":that.data,"el":that.el});
                //重新加载删除事件
                that.delTr();
            }
        }
    }
},
//全选
selectAll:function(){
    var that = this;
    $("#select_all").click(function(){
        if($("#select_all").prop("checked") == true){
          that.is_select = true;
        }else{
          that.is_select = false;
        }
        var $tr = $(that.el).children("tbody").children("tr");
        var _len = $tr.length;
        for(var i = 0; i < _len; i++){
            var item = $tr[i];
            if(that.is_select == true){
                $(item).find("input:checkbox").prop("checked",true);
            }else{
                $(item).find("input:checkbox").prop("checked",false);
            }
        }
    });
},
//多选删除
delGroup:function(){
    var that = this;
    $("#del_tr").click(function(){
        var indexArr = [];
        var $tr = $(that.el).children("tbody").children("tr");
        var _len = $tr.length;
        for(var i = 0; i < _len; i++){
            var item = $tr[i];
            if($(item).find("input:checkbox").prop("checked") == true){
                indexArr.push(i);
            }
        }
        for(var i = indexArr.length-1; i >= 0; i--){
            //注意删除是从最后一项开始删除
            //删除选中行
            $("tr[id='line"+indexArr[i]+"']").remove();
                //更新数据
                that.data.splice(indexArr[i],1);
            }
            //重新渲染表格
            paging.init({"data":that.data,"el":that.el});           
            //更改全选状态
            if(indexArr.length == _len){
                $("#select_all").prop("checked",false);
            }
            //重新加载删除事件
            that.delGroup();
            that.delTr();
    });
},
//修改行内容，使用modal组件
reviseTr:function(){
    var that = this;
    $revise_tr = $(".tr-revise");
    for(var i = 0; i < $revise_tr.length; i++){
        $revise_tr[i].index = i;
        $revise_tr[i].onclick = function(){
            that.editInfo(this.index);
        };
    }
},
//编辑模态窗信息
editInfo:function(index){
    var that = this;
    var name = $(that.el).children("tbody").children("tr").eq(index).children("td").eq(2).text();
    var age = $(that.el).children("tbody").children("tr").eq(index).children("td").eq(3).text();
    var look = $(that.el).children("tbody").children("tr").eq(index).children("td").eq(4).text();
    var score = $(that.el).children("tbody").children("tr").eq(index).children("td").eq(5).text();
    var stature = $(that.el).children("tbody").children("tr").eq(index).children("td").eq(6).text();
    
    $("#ed_name").val(name);
    $("#ed_age").val(age);
    $("#ed_look").val(look);
    $("#ed_score").val(score);
    $("#ed_stature").val(stature);

    $("#update").modal("show");
    that.reviseUpdate(index);
},
// 更新修改内容
reviseUpdate:function(index){
    var that = this;
    var revise_update = document.getElementById("revise_update");
    revise_update.onclick = function(){
        var updateInfo = {
            "name":$("#ed_name").val(),
            "age":$("#ed_age").val(),
            "look":$("#ed_look").val(),
            "score":$("#ed_score").val(),
            "stature":$("#ed_stature").val()
        };
        that.updateTr(index,updateInfo);
        $("#update").modal("hide");
    }
},
//更新修改后的行
updateTr:function(index,info){
  var that = this;
    $(that.el).children("tbody").children("tr").eq(index).children("td").eq(2).text(info.name);
    $(that.el).children("tbody").children("tr").eq(index).children("td").eq(3).text(info.age);
    $(that.el).children("tbody").children("tr").eq(index).children("td").eq(4).text(info.look);
    $(that.el).children("tbody").children("tr").eq(index).children("td").eq(5).text(info.score);
    $(that.el).children("tbody").children("tr").eq(index).children("td").eq(6).text(info.stature);
},
//点击新增
addInfo:function(){
    var that = this;
    $("#add_tr").click(function(){
        $("#modal_title").text("新增");
        $("#addmodal").modal("show");

        // 点击确认后操作
        that.addTr();

    })
},
//新增行
addTr:function(){
    var that = this;
    var add_info = document.getElementById("add_info");
    add_info.onclick = function(){
        var info = {
            "name":$("#ad_name").val(),
            "age":$("#ad_age").val(),
            "look":$("#ad_look").val(),
            "score":$("#ad_score").val(),
            "stature":$("#ad_stature").val()
        };
        //新增数据到data
        that.data.unshift(info);
        //重新加载页面
        paging.init({"data":that.data,"el":that.el});
        //隐藏模态弹窗
        $("#addmodal").modal("hide");
    }
},
//搜索
searchVal:function(){
    var that = this;
    $("#search").click(function(){
    var stxt = $("#filtertxt").val();
    //全部数组过滤，删选符合条件的值并重新渲染表格
    that.filterArr = that.filterData(stxt);
    paging.init({"data":that.filterArr,"el":that.el});
    });
},
//筛选符合条件的数据
filterData:function(value){
  var that = this;
  filterData = [];
  for(var i = 0; i < that.data.length; i++){
      var item = that.data[i];
      for(j in item){
        if(item[j].toString().indexOf(value) !== -1){
            filterData.push(item);
        }
      }
  }
  return filterData;
},
//重置搜索条件
initSearch:function(){
    var that = this;
    $("#init_search").click(function(){
        $("#filtertxt").val("");
        paging.init({"data":that.data,"el":that.el});
    });
},
}

var paging = {
el:"",  //挂载点
pageData:[],  //转化为可直接使用的DOM数据
dataCount:0,  //数据总条数
pageSize:10,  //每页显示数据数
pageCount:0,  //总页数
currentPage:1,  //当前页，默认为1
init:function(options){
    this.el = options.el;
    this.pageData = this.dataToDom(options.data);
    this.dataCount = options.data.length;
    this.pageCount = Math.ceil(options.data.length / this.pageSize);

    //数据加载
    this.currentDisplay();
},
// 将传入数据转化为dom
dataToDom:function(data){
    var domArr = [];
    for(var i = 0; i < data.length; i++){
        var dom = "<tr id='"+i+"'>" + 
            "<td><input type='checkbox' value='"+i+"'></td>" + 
            "<td>"+(i+1)+"</td>" +
            "<td>"+data[i].name+"</td>" + 
            "<td>"+data[i].age+"</td>" + 
            "<td>"+data[i].look+"</td>" + 
            "<td>"+data[i].score+"</td>" + 
            "<td>"+data[i].stature+"</td>" + 
            "<td><button class='btn btn-danger tr-del'>删除</button><span> </span><button class='btn btn-primary tr-revise'>修改</button></td>" + 
            "</tr>";
        domArr.push(dom);
    }
    return domArr;
},
//页码按钮初始化
pagingButton:function(){
    //pagingButton使用的是bootstrap分页组件
    var pageN = "";
    var that = this;
    if(that.pageCount == 1){
        var pageNav = "";
    }else if(that.pageCount <= 5){
        for(var i = 1; i <= that.pageCount; i++){
            pageN += "<li id='page"+i+"' selectPage='"+i+"'><a href='#'>"+i+"</a></li>";  
           //注意此处使用了自定义属性selectPage
        }
        var pageNav = that.getPageN(pageN);
    }else if(that.pageCount > 5){
        if(that.currentPage <= 3){
            for(var i = 1; i < 5; i++){
                pageN += "<li id='page"+i+"' selectPage='"+i+"'><a href='#'>"+i+"</a></li>";
            }
            pageN += "<li class='disabled' selectPage='dots'><span>···</span></li>" + "<li id='page"+that.pageCount+"' selectPage='"+that.pageCount+"'><a href='#'>"+that.pageCount+"</a></li>";
        }else if(that.currentPage > 3 && that.currentPage < that.pageCount - 2){
            pageN = "<li id='page1' selectPage='1'><a href='#'>1</a></li>" + "<li class='disabled' selectPage='dots'><span>···</span></li>";
            for(var i = parseInt(that.currentPage) - 2; i <= parseInt(that.currentPage) + 2; i++){
                pageN += "<li id='page"+i+"' selectPage='"+i+"'><a href='#'>"+i+"</a></li>";
            }
            pageN += "<li class='disabled' selectPage='dots'><span>···</span></li>" + "<li id='page"+that.pageCount+"' selectPage='"+that.pageCount+"'><a href='#'>"+that.pageCount+"</a></li>";
        }else if(that.currentPage >= that.pageCount - 2){
            pageN = "<li id='page1' selectPage='1'><a href='#'>1</a></li>" + "<li class='disabled' selectPage='dots'><span>···</span></li>";
            for(var i = that.pageCount - 4; i <= that.pageCount; i++){
                pageN += "<li id='page"+i+"' selectPage='"+i+"'><a href='#'>"+i+"</a></li>";
            }
        }
        var pageNav = that.getPageN(pageN);
    }

    $("#page").html("");
    $("#page").append(pageNav)  //将pageNav append 到挂载点上
},
getPageN:function(content){
 return "<nav aria-label='Page navigation'>" + 
    "<ul class='pagination'>" + 
    "<li selectPage='up'><a href='#'' aria-label='Previous'><span aria-hidden='true'>&laquo;</span></a></li>" + 
    content +
    "<li selectPage='down'><a href='#' aria-label='Next'><span aria-hidden='true'>&raquo;</span></a></li>" +
    "</ul>" +
    "</nav>";
},
//初始化默认显示第一页数据
//currentPage = 1
currentDisplay:function(){
    var that = this;
    $(that.el).children("tbody").empty();
    var firstData = (that.currentPage - 1) * that.pageSize;
    //防止最后一页没有数据
    //没有数据就重新加载到新的最后一页
    if(!that.pageData[firstData]){
      that.currentPage = that.currentPage - 1;
    }
    for(var i = (that.currentPage - 1) * that.pageSize; i < that.pageSize * that.currentPage; i++){
        $(that.el).children("tbody").append(that.pageData[i]);  //将当前页的数据append到表格上
    }

    //加载button对应事件
    that.pagingButton(); 
    that.checkCritical();
    that.selectDisplay();
    $("#page"+that.currentPage+"").addClass("active");  //当前页更改样式

    //加载所需要的操作事件
    operations.delTr();
    operations.delGroup();
    operations.selectAll();
    operations.reviseTr();
    operations.addInfo();
    operations.searchVal();
    operations.initSearch();
},
//点击页数切换表格显示数据
selectDisplay:function(){
    var that = this;
    $("li").on("click",function(){
       //对当前点击button的属性selectPage作出判断
       if($(this).attr("selectPage") == "up"){
             if(that.currentPage == 1){
                return;
             }else{
                that.currentPage--;
                $("li").removeClass("active");
                that.currentDisplay();
                that.checkCritical();
             }
       }else if($(this).attr("selectPage") == "down"){
            if(that.currentPage == that.pageCount){
                return;
            }else{
                that.currentPage++;
                $("li").removeClass("active");
                that.currentDisplay();
                that.checkCritical();
            }
       }else{
            $("li").removeClass("active");
            that.currentPage = $(this).attr("selectPage");
            that.currentDisplay();
            that.checkCritical();
        }
        console.log(that.currentPage);
    })
},
// 检查临界值，用于判断是否在第一页和最后一页
checkCritical:function(){
    var that = this;
    if(that.currentPage == 1){
        $("li:first").addClass("disabled");
    }else if(that.currentPage == that.pageCount){
        $("li:last").addClass("disabled");
    }else{
        $("li").removeClass("disabled");
    }
}
}

operations.init({"data":data,el:"#itable"});
</script>
</body>
</html>